class Carousel {
    constructor(options = {}) {
        // 默认配置
        this.config = {
            container: '#carousel',
            interval: 3000,
            speed: 500,
            showArrows: true,
            showIndicators: true,
            ...options
        };
        
        // 初始化元素
        this.container = document.querySelector(this.config.container);
        this.wrapper = this.container.querySelector('.carousel-wrapper');
        this.slides = this.wrapper.querySelectorAll('.carousel-slide');
        this.prevBtn = this.container.querySelector('#prevBtn');
        this.nextBtn = this.container.querySelector('#nextBtn');
        this.indicators = this.container.querySelector('#indicators');
        
        // 状态变量
        this.currentIndex = 0;
        this.slideCount = this.slides.length;
        this.intervalId = null;
        this.isPaused = false;
        
        // 初始化
        this.init();
    }
    
    init() {
        this.createIndicators();
        this.bindEvents();
        this.startAutoPlay();
        this.updateDisplay();
    }
    
    createIndicators() {
        if (!this.config.showIndicators) {
            this.indicators.style.display = 'none';
            return;
        }
        
        this.indicators.innerHTML = '';
        for (let i = 0; i < this.slideCount; i++) {
            const indicator = document.createElement('div');
            indicator.className = 'indicator';
            if (i === 0) indicator.classList.add('active');
            indicator.addEventListener('click', () => this.goToSlide(i));
            this.indicators.appendChild(indicator);
        }
    }
    
    bindEvents() {
        // 箭头点击事件
        if (this.prevBtn) {
            this.prevBtn.addEventListener('click', () => this.prevSlide());
        }
        if (this.nextBtn) {
            this.nextBtn.addEventListener('click', () => this.nextSlide());
        }
        
        // 鼠标悬停事件
        this.container.addEventListener('mouseenter', () => this.pause());
        this.container.addEventListener('mouseleave', () => this.resume());
        
        // 触摸事件（移动端支持）
        let touchStartX = 0;
        let touchEndX = 0;
        
        this.container.addEventListener('touchstart', (e) => {
            touchStartX = e.changedTouches[0].screenX;
            this.pause();
        });
        
        this.container.addEventListener('touchend', (e) => {
            touchEndX = e.changedTouches[0].screenX;
            this.handleSwipe(touchStartX, touchEndX);
            this.resume();
        });
    }
    
    handleSwipe(startX, endX) {
        const swipeThreshold = 50;
        const diff = startX - endX;
        
        if (Math.abs(diff) > swipeThreshold) {
            if (diff > 0) {
                this.nextSlide();
            } else {
                this.prevSlide();
            }
        }
    }
    
    updateDisplay() {
        // 更新轮播位置
        const offset = -this.currentIndex * 100;
        this.wrapper.style.transform = `translateX(${offset}%)`;
        this.wrapper.style.transition = `transform ${this.config.speed}ms ease`;
        
        // 更新指示点
        if (this.config.showIndicators) {
            const indicators = this.indicators.querySelectorAll('.indicator');
            indicators.forEach((indicator, index) => {
                indicator.classList.toggle('active', index === this.currentIndex);
            });
        }
        
        // 更新箭头显示
        if (this.prevBtn && this.nextBtn) {
            this.prevBtn.style.display = this.config.showArrows ? 'flex' : 'none';
            this.nextBtn.style.display = this.config.showArrows ? 'flex' : 'none';
        }
    }
    
    nextSlide() {
        this.currentIndex = (this.currentIndex + 1) % this.slideCount;
        this.updateDisplay();
    }
    
    prevSlide() {
        this.currentIndex = (this.currentIndex - 1 + this.slideCount) % this.slideCount;
        this.updateDisplay();
    }
    
    goToSlide(index) {
        if (index >= 0 && index < this.slideCount) {
            this.currentIndex = index;
            this.updateDisplay();
        }
    }
    
    startAutoPlay() {
        if (this.intervalId) {
            clearInterval(this.intervalId);
        }
        
        this.intervalId = setInterval(() => {
            if (!this.isPaused) {
                this.nextSlide();
            }
        }, this.config.interval);
    }
    
    pause() {
        this.isPaused = true;
    }
    
    resume() {
        this.isPaused = false;
    }
    
    stop() {
        if (this.intervalId) {
            clearInterval(this.intervalId);
            this.intervalId = null;
        }
    }
    
    updateConfig(newConfig) {
        this.config = { ...this.config, ...newConfig };
        this.createIndicators();
        this.updateDisplay();
        this.stop();
        this.startAutoPlay();
    }
}

// 初始化轮播
let carousel = new Carousel();

// 配置面板功能
function applyConfig() {
    const interval = parseInt(document.getElementById('intervalInput').value);
    const speed = parseInt(document.getElementById('speedInput').value);
    const showArrows = document.getElementById('showArrows').checked;
    const showIndicators = document.getElementById('showIndicators').checked;
    
    carousel.updateConfig({
        interval: interval,
        speed: speed,
        showArrows: showArrows,
        showIndicators: showIndicators
    });
    
    // 显示应用成功提示
    const button = event.target;
    const originalText = button.textContent;
    button.textContent = '配置已应用！';
    button.style.background = '#28a745';
    
    setTimeout(() => {
        button.textContent = originalText;
        button.style.background = '#007bff';
    }, 2000);
}

// 动态添加图片功能（可选）
function addImage(src, alt = '') {
    const slide = document.createElement('div');
    slide.className = 'carousel-slide';
    
    const img = document.createElement('img');
    img.src = src;
    img.alt = alt;
    
    slide.appendChild(img);
    carousel.wrapper.appendChild(slide);
    
    // 重新初始化轮播
    carousel.slides = carousel.wrapper.querySelectorAll('.carousel-slide');
    carousel.slideCount = carousel.slides.length;
    carousel.createIndicators();
}

// 动态移除图片功能（可选）
function removeImage(index) {
    if (carousel.slideCount > 1 && index >= 0 && index < carousel.slideCount) {
        carousel.wrapper.removeChild(carousel.slides[index]);
        
        // 重新初始化轮播
        carousel.slides = carousel.wrapper.querySelectorAll('.carousel-slide');
        carousel.slideCount = carousel.slides.length;
        if (carousel.currentIndex >= carousel.slideCount) {
            carousel.currentIndex = carousel.slideCount - 1;
        }
        carousel.createIndicators();
        carousel.updateDisplay();
    }
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', () => {
    // 可以在这里添加额外的初始化逻辑
    console.log('自动滑动图片组件已初始化');
});
